﻿using System.Collections.ObjectModel;
using BestCode.Creds.Data;
using BestCode.Creds.Entities;

namespace BestCode.Creds.Business
{
    public class TemplateBusiness : BusinessBase<Template>
    {
        private ITemplateDao dao = DataFactory.Current.GetTemplateDao();

        public TemplateBusiness()
        {
            setDao(dao);                
        }

        public override void PostSave(Template entity)
        {
            //saving file from file path

            AttachmentBusiness attachmentBusiness = new AttachmentBusiness();

            if (entity.AttachmentId.HasValue)// then update attachment
            {
                var attach = attachmentBusiness.Get(entity.AttachmentId.Value);
                attach.FileName = entity.FaceImagePath;
                attach.ExtensionType = attach.FileName.Substring(attach.FileName.LastIndexOf('.'));

                if (System.IO.File.Exists(entity.FaceImagePath))
                    attach.MediaContent = System.IO.File.ReadAllBytes(entity.FaceImagePath);
                attachmentBusiness.Save(attach);

            }
            else
            {
                var attach = new Attachment();
                attach.FileName = entity.FaceImagePath;
                attach.ExtensionType = attach.FileName.Substring(attach.FileName.LastIndexOf('.'));
                if (System.IO.File.Exists(entity.FaceImagePath))
                    attach.MediaContent = System.IO.File.ReadAllBytes(entity.FaceImagePath);
                attachmentBusiness.Save(attach);

                //updating template
                var templateData = DataFactory.Current.GetTemplateDao();
                entity.AttachmentId = attach.Id;
                templateData.Update(entity);

            }



            
        }


        public override ObservableCollection<Template> SearchByFilter(string parameter)
        {
            return new ObservableCollection<Template>(dao.GetByFilter(parameter));
        }

        public Template GetAnverseFaceByEntity(int entityId)
        {
            return dao.GetAnverseFaceByEntity(entityId);
        }

        public Template GetReverseFaceByEntity(int entityId)
        {
            return dao.GetReverseFaceByEntity(entityId);
        }
    }
}
